<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * Loads and displays inherit views in Kohana view files.
 * See inherit_view_demo.php for more info.
 *
 * @package    Inherit_View
 * @author     homm
 * @copyright  (c) 2009 homm
 * @license    http://kohanaphp.com/license.html
 */
class Inherit_View extends View {

	protected $class_name = NULL;
	
	/**
	 * Sets the view filename.
	 *
	 * @chainable
	 * @param   string  view filename
	 * @param   string  view file type
	 * @return  object
	 */
	public function set_filename($name, $type = NULL)
	{
		parent::set_filename($name, $type);
		
		// no slashes allowed in class names.
		$this->class_name = str_replace('/', '_', $name).'_View';
		
		return $this;
	}
	/**
	 * Creates a new View using the given parameters.
	 *
	 * @param   string  view name
	 * @param   array   pre-load data
	 * @param   string  type of file: html, css, js, etc.
	 * @return  object
	 */
	public static function factory($name = NULL, $data = NULL, $type = NULL)
	{
		return new Inherit_View($name, $data, $type);
	}

	/**
	 * Renders a view.
	 *
	 * @param   boolean   set to TRUE to echo the output instead of returning it
	 * @param   callback  special renderer to pass the output through
	 * @return  string    if print is FALSE
	 * @return  void      if print is TRUE
	 */
	public function render($print = FALSE, $renderer = FALSE)
	{
		if (empty($this->kohana_filename))
			throw new Kohana_Exception('core.view_set_filename');

		if (is_string($this->kohana_filetype))
		{
			// Load the file with view onleonce
			require_once($this->kohana_filename);

			// Buffering on
			ob_start();

			// Merge global and local data, local overrides global with the same name
			new $this->class_name(array_merge(self::$kohana_global_data, $this->kohana_local_data), Kohana::$instance);
			
			// Fetch the output and close the buffer
			$output = ob_get_clean();

			if ($renderer !== FALSE AND is_callable($renderer, TRUE))
			{
				// Pass the output through the user defined renderer
				$output = call_user_func($renderer, $output);
			}

			if ($print === TRUE)
			{
				// Display the output
				echo $output;
				return;
			}
		}
		else
		{
			// Set the content type and size
			header('Content-Type: '.$this->kohana_filetype[0]);

			if ($print === TRUE)
			{
				if ($file = fopen($this->kohana_filename, 'rb'))
				{
					// Display the output
					fpassthru($file);
					fclose($file);
				}
				return;
			}

			// Fetch the file contents
			$output = file_get_contents($this->kohana_filename);
		}

		return $output;
	}
}